<template>
  <a-card>
    <p style="font-size: 18px; text-align: center">生产材料退库申请单</p>
    <br />
    <!-- 单据 -->
    <a-form-model ref="ruleForm" :model="Form" v-bind="layout" :rules="rules"
      ><!-- 顶部的信息 -->
      <a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据号">
            <a-input
              style="border: 0"
              v-model="Form.document"
              disabled
            ></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据日期">
            <a-date-picker
              v-model="Form.document_date"
              type="date"
              placeholder="请选择时间"
              style="width: 100%"
              @change="
                (a, b) => {
                  this.Form.a = a;
                  this.Form.document_date = b;
                  this.Form.balance = b;
                }
              "
            />
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="仓库名称" prop="applicationDepot_dictText">
            <a-input
              v-model="Form.applicationDepot_dictText"
              showSearch
              style="width: 100%"
              disabled
            >
            </a-input>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="产成品仓库" prop="finishedProductDepot">
            <a-input
              placeholder=""
              v-model="Form.finishedProductDepot"
              disabled
            >
            </a-input>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="库存组织" prop="pk_calbody">
            <a-input v-model="Form.pk_calbody" disabled style="width: 100%">
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="领料员">
            <a-select
              v-model="Form.picker"
              @change="getPickerId"
              @search="searchUserInfoList"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in UserList"
                :key="item.userId"
                :value="item.workNo + '|' + item.userName"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="公司" prop="pk_corp">
            <a-input v-model="Form.pkCorp_dictText" disabled></a-input>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="产成品分类" prop="finishGoodsType">
            <a-input
              v-model="Form.finishedProductType_dictText"
              disabled
              style="width: 100%"
            >
            </a-input>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="所属分厂" prop="ownedBranch">
            <a-input
              v-model="Form.ownedBranch"
              style="width: 100%"
              :tree-data="ownedBranchList"
              disabled
            >
            </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>

    <!-- 生成原单按钮组件 -->
    <productionMaterialReturnApplication
      @select-data="setGoodsListInfoByOrigin"
    ></productionMaterialReturnApplication>

    <!-- //TODO: -->
    <!-- 单据对应表格 -->
    <a-table
      :columns="columns"
      :data-source="dataSource"
      style="margin-top: 10px"
      :pagination="false"
      :scroll="{ x: 4000 }"
      :key="randomKey"
    >
      <!-- 仓库编码 -->
      <span slot="depotNo" slot-scope="text, record">
        <a-select
          v-model="record.depotNo"
          showSearch
          style="width: 100%"
          @change="setGoodsList(record.key)"
        >
          <a-select-option
            v-for="item in storageList"
            :key="item.depotNo"
            :value="item.depotNo + '|' + item.depotName"
          >
            {{ item.depotNo }} {{ item.depotName }}
          </a-select-option>
        </a-select>
      </span>

      <!-- 库位 -->
      <span slot="depotLocation" slot-scope="text, record">
        <a-tree-select
          v-model="record.depotLocation"
          style="width: 100%"
          :tree-data="record.positionList"
          allow-clear
        ></a-tree-select>
      </span>
      <!-- 仓位 -->
      <span slot="position" slot-scope="text, record">
        <a-tree-select
          v-model="record.position"
          style="width: 100%"
          :tree-data="record.positionList"
          allow-clear
        ></a-tree-select>
      </span>

      <!-- 存货编码 -->
      <span slot="inventoryName" slot-scope="text, record">
        <a-select
          v-model="record.inventoryName"
          style="width: 100%"
          @change="getInventoryInfo(record.key)"
          @search="handleInventoryInfoSearch"
          showSearch
        >
          <a-select-option
            v-for="item in goodsList"
            :key="item.inventoryId"
            :value="
              item.inventoryNo +
              '|' +
              item.inventoryName +
              '|' +
              item.standardModel +
              '|' +
              item.unit
            "
          >
            {{ item.inventoryNo }} {{ item.inventoryName }}
            {{ item.standardModel }}
          </a-select-option>
        </a-select>
      </span>

      <!-- 辅助单位 -->
      <!-- <span slot="auxiliary_unit" slot-scope="text, record">
        <a-select
          v-model="record.auxiliary_unit"
          style="width: 100%"
          @change="disableUnit(record.key)"
        >
          <a-select-option
            v-for="item in Auxiliary_Unitlist"
            :key="item.title"
            :value="item.value"
          >
            {{ item.title }}
          </a-select-option>
        </a-select>
      </span> -->

      <!-- 数量 -->
      <span slot="quantity" slot-scope="text, record">
        <a-input-number
          v-model="record.quantity"
          :min="0"
          :precision="precision"
        />
      </span>

      <!-- 批次号 -->
      <span slot="batchNumber" slot-scope="text, record">
        <a-select
          v-model="record.batchNumber"
          style="width: 100%"
          @change="getBatchNumberInfo(record.key)"
        >
          <a-select-option
            v-for="(item, index) in record.BatchList"
            :key="index"
            :value="item"
          >
            {{ item }}
          </a-select-option>
        </a-select>
      </span>

      <!-- 产成品分类 -->
      <!-- <span slot="finishedProductType" slot-scope="text, record">
        <a-tree-select
          :tree-data="finishGoodsTypeList"
          @change="getFinishGoodsTypeId(record.key)"
          v-model="record.finishedProductType"
          style="width: 100%"
        >
        </a-tree-select>
      </span> -->

      <!-- 出库日期 -->
      <span slot="deliveryDate" slot-scope="text, record">
        <a-date-picker
          @change="formatDeliveryDate(record.key)"
          v-model="record.deliveryDate"
          type="date"
          placeholder="请选择时间"
          style="width: 100%"
        />
      </span>
      =
      <!-- 出菇领料金额 -->
      <span slot="amountOfFruitPicking" slot-scope="text, record">
        <a-input-number
          v-model="record.amountOfFruitPicking"
          :min="0"
          :precision="amountPrecision"
        />
      </span>
      <!-- 备注 -->
      <span slot="remark" slot-scope="text, record">
        <a-input v-model="record.remark"> </a-input>
      </span>

      <template slot="action" slot-scope="text, record">
        <span v-if="record.isNew">
          <a @click="cancle(record.key)">取消</a>
        </span>
        <span v-else>
          <a-popconfirm
            ok-text="确定"
            cancel-text="取消"
            @confirm="Delete(record.id)"
          >
            <template slot="title">
              <p>确定删除？</p>
            </template>
            <a type="danger"> 删除 </a>
          </a-popconfirm>
        </span>
      </template>
    </a-table>
    <!-- <a-button
      style="width: 100%; margin-top: 16px; margin-bottom: 8px"
      type="dashed"
      icon="plus"
      @click="newMember"
      >添加</a-button
    > -->

    <div style="margin-top: 20px">
      <!-- 单据 -->
      <a-form-model
        :model="Form"
        v-bind="layout"
        :rules="rules2"
        ref="ruleForm2"
        ><!-- 顶部的信息 -->
        <a-row>
          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核人" prop="inspector">
              <a-select
                v-model="Form.inspector"
                showSearch
                @change="setInspector"
                style="width: 100%"
              >
                <a-select-option
                  v-for="item in inspectorList"
                  :key="item.userId"
                  :value="item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核日期" prop="">
              <a-date-picker
                v-model="Form.balance"
                type="date"
                style="width: 100%"
                disabled
              />
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="制单人" prop="">
              <a-input disabled v-model="Form.singleProducer"> </a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>

      <!-- 提交按钮组  -->
      <div style="margin-top: 20px">
        <center>
          <a-button @click="Save" style="margin-right: 20px"> 保存 </a-button>

          <a-button style="margin-right: 20px" disabled> 审核 </a-button>
        </center>
      </div>
    </div>
  </a-card>
</template>

<script>
import productionMaterialReturnApplication from "@/components/common/productionMaterialReturnApplication";
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口

// import { ZiDianBiaoHttp } from "@/services/modules/ZiDianBiao.js";
// const zdbHttp = new ZiDianBiaoHttp(); // 字典表

import moment from "moment";
import { mapState, mapGetters } from "vuex";

// 1. 导入
// import footerCommonBar from "../../components/common/footerCommonBar";

// 规则

// 物品信息表格
const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
  },

  // {
  //   title: "仓库编码",
  //   dataIndex: "depotNo",
  //   key: "depotNo",
  //   align: "center",
  //   width: "7%",
  //   scopedSlots: { customRender: "depotId_dictText" },
  // },
  {
    title: "仓库名称",
    dataIndex: "depotId_dictText",
    key: "depotId_dictText",
    align: "center",
  },
  // {
  //   title: "库位",
  //   dataIndex: "depotLocation",
  //   key: "depotLocation",
  //   align: "center",
  //   scopedSlots: { customRender: "depotLocation" },
  // },
  // {
  //   title: "仓位",
  //   dataIndex: "position",
  //   key: "position",
  //   align: "center",
  //   scopedSlots: { customRender: "position" },
  // },
  {
    title: "存货编码",
    dataIndex: "invcode",
    key: "invcode",
    align: "center",

    scopedSlots: { customRender: "invcode" },
  },
  {
    title: "存货名称",
    dataIndex: "invname",
    key: "invname",
    width: "10%",
    align: "center",
    scopedSlots: { customRender: "invname" },
  },
  {
    title: "规格型号",
    dataIndex: "invspec",
    key: "invspec",
    align: "center",
  },
  {
    title: "单位",
    key: "measname",
    dataIndex: "measname",
    align: "center",
  },
  {
    title: "单价",
    key: "unitPrice",
    dataIndex: "unitPrice",
    align: "center",
    scopedSlots: { customRender: "unitPrice" },
  },
  {
    title: "金额",
    key: "money",
    dataIndex: "money",
    align: "center",
    scopedSlots: { customRender: "money" },
  },
  // {
  //   title: "批次号",
  //   key: "batchNumber",
  //   dataIndex: "batchNumber",
  //   align: "center",
  //   scopedSlots: { customRender: "batchNumber" },
  // },
  // {
  //   title: "现存数量",
  //   key: "existingQuantity",
  //   dataIndex: "existingQuantity",
  //   align: "center",
  //   scopedSlots: { customRender: "existingQuantity" },
  // },
  {
    title: "数量",
    key: "quantity",
    dataIndex: "quantity",
    align: "center",
    scopedSlots: { customRender: "quantity" },
  },

  {
    title: "源单单号",
    key: "sourceNumber",
    dataIndex: "sourceNumber",
    align: "center",
  },

  // {
  //   title: "产成品分类",
  //   key: "finishedProductType",
  //   dataIndex: "finishedProductType",
  //   align: "center",
  //   scopedSlots: { customRender: "finishedProductType" },
  // },
  // {
  //   title: "出库日期",
  //   key: "deliveryDate",
  //   dataIndex: "deliveryDate",
  //   align: "center",
  //   scopedSlots: { customRender: "deliveryDate" },
  // },
  {
    title: "出菇领料金额",
    key: "amountOfFruitPicking",
    dataIndex: "amountOfFruitPicking",
    align: "center",
    scopedSlots: { customRender: "amountOfFruitPicking" },
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    align: "center",
    scopedSlots: { customRender: "remark" },
  },
];

export default {
  // 2. 注册
  components: {
    productionMaterialReturnApplication,
    // footerCommonBar,
  },
  computed: {
    // 获取本地数据
    ...mapState("user", { currUser: "info", currPost: "position" }),
    ...mapGetters({
      getDepsInfo: "user/getDepsInfo",
    }),
    // ...mapState("setting", ["isMobile"]),
  },
  data() {
    return {
      rules2: {
        responsiblePerson: [
          {
            required: true,
            trigger: "blur",
            message: "选择负责人",
          },
        ],
        inspector: [
          {
            required: true,
            trigger: "blur",
            message: "选择审核人",
          },
        ],
      },
      rules: {
        applicationDepot_dictText: [
          {
            required: true,
            trigger: "blur",
            message: "选择仓库名称",
          },
        ],
        finishedProductDepot: [
          {
            required: true,
            trigger: "blur",
            message: "选择产成品仓库",
          },
        ],
        // sendReceiveType: [
        //   {
        //     required: true,
        //     trigger: "blur",
        //     message: "选择收发类别",
        //   },
        // ],
        pk_calbody: [
          {
            required: true,
            trigger: "blur",
            message: "选择库存组织",
          },
        ],
        ownedBranch: [
          {
            required: true,
            trigger: "change",
            message: "选择所属分厂",
          },
        ],
        finishedProductType: [
          {
            required: true,
            trigger: "change",
            message: "选择产成品分类",
          },
        ],
      },
      precision: 3, //销售系统保留3位小数
      amountPrecision: 2, //销售系统金额保留2位小数
      // ----- 申请的表单内容信息 -----
      Form: {
        document: "", // 申请单号
        document_date: moment().format("YYYY-MM-DD"), // 单据日期 // 日期
        sendReceiveType: "", // 收发类别名称
        sendReceiveTypeId: "", // 收发类别Id
        finishedProductDepot: "", //产成品仓库
        finishedProductDepotId: "", //产成品仓库ID
        supplier: "", //供应商
        supplierId: "", //供应商Id
        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        balance: moment().format("YYYY-MM-DD"), // 审核日期
        singleProducer: this.$store.state.user.info.username, // 制单人名称
        singleProducerId: this.$store.state.user.info.id, // 制单人Id

        pk_corp: "山东七河生物科技股份有限公司",
        pk_corpId: "1001",

        storage: "", //仓库名称
        storageNo: "", // 申请仓库编码
        storageId: "", // 仓库名称ID
        ownedBranch: "", // 所属公司

        finishedProductType_dictText: "", //产成品分类
        finishedProductType: "", //产成品分类
      },

      // 字典表等数据

      storageList: [], // 仓库列表，所属仓库，产成品仓库
      supplierList: [], //供应商名称
      goodsList: [], // 存货列表
      SendReceiveList: [], // 收发类别列表
      Auxiliary_Unitlist: [], // 辅助单位列表
      batchNumberList: [], // 批次号列表
      finishGoodsTypeList: [], //产成品分类列表

      customerNameList: [], //供应商列表
      farmerList: [], //农户列表

      InventoryOrganizationList: [], // 库存组织列表
      UserList: [], // 库管员列表
      workNoList: [], // 判重使用
      pk_corpList: [], // 公司列表
      ownedBranchList: [], //分厂列表

      responsiblePersonList: [], // 负责人列表
      inspectorList: [], // 审核人列表
      inspectorIdList: [], // 审核人Id列表

      updateTag: true, // 修改标志
      // ------- 表格 --------
      // 格式
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      // 列表
      columns,
      dataSource: [],
      selectedRowKeys: [],
      randomKey: 0,
    };
  },
  watch: {
    $route: function (to) {
      if (to.path == "/productionMaterialOutCancelApply") {
        this.getRouterParam();
      }
    },
  },
  // 生命周期函数
  mounted() {
    this.judgeDocument();//判断单据号是否为空
    this.setColumns(); // 生成多条数据
    this.getApplyOrder(); // 获取申请单号
    this.getwarehouseInfo(); //获取仓库，所属仓库和产成品仓库接口
    this.getSupplierInfo(); //供应商信息列表
    this.getSendReceiveList(); //获取收发类别
    this.getFinishGoodsTypeList(); //获取产成品分类列表
    this.getSyncInventoryOrganizationList();
    this.getpk_corpList();
    this.getownedBranchTree(); //获取分厂列表
    this.getResponsiblePersonList(); // 获取负责人列表
    this.getInspectorList(); // 获取审核人
    this.getRouterParam();
  },
  methods: {
      // ————判断单据号是否为空————
    judgeDocument(){
      setTimeout(() =>{
        if (this.Form.document === "") {
        this.$message.error("未获取到单据号,请刷新页面重试");
      }},3000)
    },
    // 获取公司
    getpk_corpList() {
      comHttp.getpk_corpList().then((res) => {
        console.log("公司", res);
        this.pk_corpList = res.result;

        this.changeCorpData(this.pk_corpList);

        console.log(123124, this.pk_corpList);
      });
    },
    // 获取公司改变用友传递过来的数据为组件能识别的数据
    changeCorpData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.unitcode + " " + element.unitname;
        element["value"] = element.unitcode + "|" + element.unitname;
        element["children"] = element.syncCompanyEntityList;
        element["key"] = element.id;

        if (element.children) {
          this.changeCorpData(element.children);
        }
      });
    },

    // 获取公司获取公司Id
    getpk_corpId(value, label, extra) {
      console.log(extra);

      let arr = this.Form.pk_corp.split("|");
      this.Form.pk_corpId = arr[0];
      this.Form.pk_corp = arr[1];
      console.log(this.Form.pk_corp, 333333333);
    },

    // 获取分厂列表
    getownedBranchTree() {
      comHttp.getDepartmentList().then((res) => {
        // let tree = this.resetTree(res.result);
        console.log("获取部门树+++++++++++::::", res);
        this.ownedBranchList = res.result;
        this.changeownedBranchData(this.ownedBranchList);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeownedBranchData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.deptname;
        element["children"] = element.syncDepartmentFilesEntityList;
        element["key"] = element.pkDeptdoc;
        element["value"] = element.pkDeptdoc;

        if (element.children) {
          this.changeownedBranchData(element.children);
        }
      });
    },
    // 部门下拉框选择
    changeTreeNode(key, value) {
      console.log("key", key);
      console.log("value", value);
      this.Form.ownedBranch = value[0];
      this.Form.ownedBranchId = key;
      console.log("选择的值::::", this.Form.ownedBranch);
      console.log("ownedBranchId::::", this.Form.ownedBranchId);
    },
    // 客户模糊搜索
    searchFarmer(value) {
      if (value == "") {
        this.$message.error("请输入客户名称！");
      } else if (value == " ") {
        value = "";
        console.log("value", value);
        this.$message.error("请输入真实数据！");
      } else {
        this.customerNameList = [];
        let data = "?customerName=" + value + "&custflag=0,2";
        comHttp.getCustomerInfoByName(data).then((res) => {
          console.log("res", res);
          for (let i = 0; i < res.result.length; i++) {
            let data = {
              id: res.result[i].pkCumandoc,
              customerCode: res.result[i].custcode,
              name: res.result[i].custname,
            };
            this.farmerList.push(data);
          }
        });
      }
    },
    // 客户选择的处理函数
    changeFarmer(value) {
      console.log("客户选择处理函数", value);
      let array = value.split("|");
      this.Form.farmerCode = array[0]; //客户编码
      this.Form.farmer = array[1]; //客户名称
      this.Form.farmerId = array[2]; //客户Id
      console.log("this.form.customerId", this.Form.customerId);
      let id = array[2]; //客户id
      console.log("id", id);
    },
    // 客户模糊搜索
    searchCustomer(value) {
      if (value == "") {
        this.$message.error("请输入客户名称！");
      } else if (value == " ") {
        value = "";
        console.log("value", value);
        this.$message.error("请输入真实数据！");
      } else {
        this.customerNameList = [];
        let data = "?customerName=" + value + "&custflag=3,1";
        comHttp.getCustomerInfoByName(data).then((res) => {
          console.log("res", res);
          for (let i = 0; i < res.result.list.length; i++) {
            let data = {
              id: res.result.list[i].pkCumandoc,
              customerCode: res.result.list[i].custcode,
              name: res.result.list[i].custname,
            };
            this.customerNameList.push(data);
          }
        });
      }
    },
    // 客户选择的处理函数
    changeCustomer(value) {
      console.log("客户选择处理函数", value);
      let array = value.split("|");
      this.Form.supplierCode = array[0]; //客户编码
      this.Form.supplier = array[1]; //客户名称
      this.Form.supplierId = array[2]; //客户Id
      console.log("this.form.customerId", this.Form.supplierId);
      let id = array[2]; //客户id
      console.log("id", id);
    },
    // 获取产成品分类列表
    getFinishGoodsTypeList() {
      comHttp.GetSaveCargoClassification().then((res) => {
        console.log("产成品分类列表", res);

        this.finishGoodsTypeList = res.result;
        this.changeFinishGoodsType(this.finishGoodsTypeList);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeFinishGoodsType(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.invclassname;
        element["children"] = element.syncInventoryClassificationEntityList;
        element["key"] = element.invclassname;
        element["value"] = element.pkInvcl;

        if (element.children) {
          this.changeFinishGoodsType(element.children);
        }
      });
    },

    // 处理产成品分类
    setFinishGoodsType(key, value) {
      console.log("key======>", key);
      console.log("value======>", value);
      console.log("this.forafdslfdsfdsfd", this.Form.finishGoodsType);

      // console.log("value11111111111", key);
      // let array = target.finishGoodsType.split("|");
      // // console.log("array===", array);
      // target.finishGoodsTypeId = array[0];
      // target.finishGoodsType = array[1];
      // console.log("target.finishGoodsTypeId", target);
    },
    // 获取库存组织列表
    getSyncInventoryOrganizationList() {
      comHttp.getSyncInventoryOrganizationList().then((res) => {
        console.log("库存组织", res);
        this.InventoryOrganizationList = res.result;
      });
    },
    // 获取库存组织Id
    getpk_calbodyId(value, options) {
      this.Form.pk_calbodyId = options.key;
      // console.log(this.Form.pk_calbodyId, 222222222);
    },

    // 库管员列表
    getcwhsmanagerId(value, option) {
      this.Form.cwhsmanagerid = option.key;
      console.log("this.getcwhsmanagerId", this.Form.cwhsmanagerid);
    },

    // 查询人员信息列表
    searchUserInfoList(value) {
      this.UserList = [];
      this.workNoList = [];
      if (value != "") {
        let queryPath = "?username=" + value;
        comHttp.getUserInfoByUserName(queryPath).then((res) => {
          for (let i = 0; i < res.result.list.length; i++) {
            if (!this.workNoList.includes(res.result.list[i].workNo)) {
              let data = {
                userName: res.result.list[i].username,
                userId: res.result.list[i].id,
                workNo: res.result.list[i].workNo,
              };
              this.UserList.push(data);
              this.workNoList.push(res.result.list[i].workNo);
            }
          }
        });
      }
    },
    //通过数据源单生成数据
    setGoodsListInfoByOrigin(data) {
      console.log("传递过来的数据:::::", data);
      this.Form.pickingContentId = data.pickingContentId;
      // 给表单赋值
      // 部门
      this.Form.deptId = data.deptId;
      this.Form.deptId_dictText = data.deptId_dictText;
      // 仓库名称
      if (
        data.applicationDepot_dictText == "" ||
        data.applicationDepot_dictText == null
      ) {
        this.Form.applicationDepot = data.goodsList[0].depotId;
        this.Form.applicationDepot_dictText =
          data.goodsList[0].depotId_dictText;
      } else {
        this.Form.applicationDepot = data.applicationDepot;
        this.Form.applicationDepot_dictText = data.applicationDepot_dictText;
      }

      // 产成品仓库
      this.Form.finishedProductDepotId = data.finishedProductDepot;
      this.Form.finishedProductDepot = data.finishedProductDepot_dictText;
      // 库存组织
      this.Form.pk_calbodyId = data.pkCalbody;
      this.Form.pk_calbody = data.pkCalbody_dictText;
      // 领料员
      this.$set(this.Form, "pickerId", data.picker);
      this.$set(this.Form, "picker", data.picker_dictText);
      // this.Form.pickerId = data.picker;
      // this.Form.picker = data.picker_dictText;
      // 公司
      // this.Form.pkCorp = data.pkCorp;
      // this.Form.pkCorp_dictText = data.pkCorp_dictText;
      this.Form.pkCorp = "1001";
      this.Form.pkCorp_dictText = "山东七河生物科技股份有限公司";
      // 产成品分类
      this.Form.finishGoodsType = data.finishedProductType;
      this.Form.finishedProductType_dictText =
        data.finishedProductType_dictText;
      // 所属分厂
      this.Form.ownedBranchId = data.ownedBranch;
      this.Form.ownedBranch = data.ownedBranch_dictText;

      // 库管员
      this.Form.cwhsmanagerid_dictText = data.cwhsmanagerid_dictText;
      this.Form.cwhsmanagerid = data.cwhsmanagerid;

      // 客户
      this.Form.clientId = data.clientId;
      this.Form.clientId_dictText = data.clientId_dictText;
      // 业务类型
      this.Form.cbiztype = data.cbiztype;
      this.Form.cbiztype_dictText = data.cbiztype_dictText;

      // 收发类别
      this.Form.sendReceiveType_dictText = data.sendReceiveType_dictText;
      this.Form.sendReceiveType = data.sendReceiveType;

      this.dataSource = data.goodsList; // 给列表赋值

      this.dataSource.forEach((element) => {
        element.remark = "";
        // element.sourceNumber = element.document;
      });
    },
    // 领料员列表处理函数
    getPickerId(value, option) {
      this.Form.pickerId = option.key;
      this.Form.picker = value;
      this.$set(this.Form, "pickerId", option.key);
      this.$set(this.Form, "picker", value);
    },
    changecwhsmanager(value, option) {
      this.Form.cwhsmanagerid = option.key;
      this.Form.cwhsmanager = value;
    },
    // !下拉框搜索
    handleInventoryInfoSearch(value) {
      if (value.match(/^[ ]*$/)) {
        this.$message.error("请输入真实数据！");
      } else {
        let queryPath = "?name=" + value;
        this.goodsList = [];
        comHttp.getSearchInventoryInformationFile(queryPath).then((res) => {
          console.log("res", res.result);
          for (let i = 0; i < res.result.length; i++) {
            let data = {
              inventoryId: res.result[i].pkInvbasdoc, // 存货 id
              inventoryName: res.result[i].invname,
              inventoryNo: res.result[i].invcode,
              standardModel: res.result[i].invspec,
              unit: res.result[i].measname,
            };
            this.goodsList.push(data);
          }
          console.log("this.goodsList====>", this.goodsList);
        });
      }
    },
    // 获取路由参数
    getRouterParam() {
      console.log("查询参数:::", this.$route.query.Id);
      // 通过出入库id 查询出入库信息
      if (typeof this.$route.query.Id == "undefined") {
        console.log("常规跳转");
      } else {
        this.setInitInfo(this.$route.query.Id);
      }
    },
    // 通过路由跳转，设置初始化信息
    async setInitInfo(id) {
      this.updateTag = false;
      comHttp.getOutStorageApplyInfoById("?id=" + id).then((res) => {
        this.dataSource = [];

        console.log("通过Id查询出来的信息::::", res);
        this.otherId = res.result.list[0].otherId; // 表一 Id
        this.Form = {
          id: res.result.list[0].otherId, // 表一 Id
          document: res.result.list[0].document, // 单据号
          document_date: res.result.list[0].documentDate, // 单据日期

          // 供应商
          supplier: res.result.list[0].supplier_dictText,
          supplierId: res.result.list[0].supplier,

          // 仓库名称
          applicationDepot_dictText: res.result.list[0].storname,
          depotId: res.result.list[0].pkStordoc,

          // 产成品仓库
          finishedProductDepot:
            res.result.list[0].finishedProductDepot_dictText,
          finishedProductDepotId: res.result.list[0].finishedProductDepot,

          // 产成品分类
          finishedProductType: res.result.list[0].finishedProductType,
          finishedProductType_dictText:
            res.result.list[0].finishedProductTypeDictText,

          // 所属公司
          pkCorp_dictText: res.result.list[0].pkCorp_dictText, //所属公司
          pk_corpId: res.result.list[0].pkCorp, //所属公司ID

          sendReceiveType: res.result.list[0].sendReceiveType_dictText, // 收发类别
          sendReceiveTypeId: res.result.list[0].sendReceiveType, // 收发类别Id

          responsiblePerson: res.result.list[0].responsiblePerson_dictText, // 负责人
          responsiblePersonId: res.result.list[0].responsiblePerson,

          inspector: res.result.list[0].inspector_dictText, // 审核人
          inspectorId: res.result.list[0].inspector,

          singleProducer: res.result.list[0].singleProducer_dictText, // 制单人
          singleProducerId: res.result.list[0].singleProducer,
          balance: res.result.list[0].balance, //审核日期

          pickerId: res.result.list[0].picker, //领料员ID
          picker: res.result.list[0].picker_dictText, //领料员
          cwhsmanagerid: res.result.list[0].cwhsmanagerid, //库管员ID
          cwhsmanager: res.result.list[0].cwhsmanagerid_dictText, //库管员
          pk_calbodyId: res.result.list[0].pkCalbody, //库存组织Id
          pk_calbody: res.result.list[0].pkCalbody_dictText, //库存组织
          farmerId: res.result.list[0].farmer, //农户ID
          farmer: res.result.list[0].farmer_dictText, //农户
          ownedBranchId: res.result.list[0].ownedBranch, //所属分厂
          ownedBranch: res.result.list[0].ownedBranch_dictText, //所属分厂
        };

        for (let i = 0; i < res.result.list.length; i++) {
          let data = {
            key: i + 1,
            id: res.result.list[i].twoId, // 表二 Id
            otherId: res.result.list[i].otherId, // 表一Id
            isNew: false,

            depotId: res.result.list[i].depotId, // 仓库Id
            depotNo: res.result.list[i].storcode, // 仓库编码
            depotId_dictText: res.result.list[i].storname, // 仓库名称

            depotLocation: res.result.list[i].depotLocation, // 库位
            position: res.result.list[i].position, // 仓位

            inventoryId: res.result.list[i].inventoryId, // 存货Id
            invcode: res.result.list[i].invcode, // 存货编码
            invname: res.result.list[i].invname, // 存货名称
            invspec: res.result.list[i].invspec, // 规格型号
            measname: res.result.list[i].measname, // 单位
            quantity: res.result.list[i].quantity, // 数量
            unitPrice: res.result.list[i].unitPrice, // 单价
            money: res.result.list[i].money, // 金额
            sourceNumber: res.result.list[i].sourceNumber, // 源单单号
            batchNumber: res.result.list[i].batchNumber, // 批次号
            finishedProductType: res.result.list[i].finishedProductType, // 产成品分类Id
            finishedProductTypeId: res.result.list[i].finishedProductType, // 产成品分类
            amountOfFruitPicking: res.result.list[i].amountOfFruitPicking, // 出菇领料金额

            deliveryDate: res.result.list[i].deliveryDate, // 出库日期
            remark: res.result.list[i].remarks, // 备注
          };

          this.dataSource.push(data);
        }
      });
    },

    // 获取所属仓库,表格触发事件
    getstorageUnitId(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      let array = target.storageUnit.split("|");
      target.storageUnitNo = array[0]; // 仓库id
      target.storageUnit = array[1]; // 仓库名称

      let SotrageInfo = this.storageList.filter(
        (item) => item.depotNo === array[0]
      )[0];
      target.storageUnitId = SotrageInfo.depotId;
      console.log("表格所属仓库::::", target.storageUnitId);
    },
    // 默认设置五行，让用户方便添加
    setColumns() {
      let size = 1;
      this.DataSource = [];
      for (let i = 0; i < size; i++) {
        let data = {
          key: i + 1,
          isNew: true,
          depotId: "", // 仓库Id
          depotNo: "", // 仓库编码
          depotName: "", // 仓库名称
          depotLocation: "", // 库位
          position: "", // 仓位

          inventoryId: "", // 存货Id
          inventoryNo: "", // 存货编码
          inventoryName: "", //  存货名称
          standardModel: "", // , 规格型号
          unit: "", // 单位
          existingQuantity: 0, //现存数量
          quantity: "", // 	数量
          unitPrice: "", // 单价
          money: "", // 金额
          amountOfFruitPicking: "", // 金额

          batchNumber: "", // 批次号
          finishedProductType: "", //产成品分类
          finishedProductTypeId: "", // 产成品分类Id

          sourceNumber: "", // 源单单号（外键）
          deliveryDate: "", // 出库日期
          remark: "", // 备注

          goodsList: [], // 物品信息列
          BatchList: [], // 批次列表
          positionList: [], // 仓位列表
        };
        this.DataSource.push(data);
      }
      // console.log("默认加载的数据::::",this.DataSource)
    },

    // 所属仓库，仓库名称，产成品仓库
    getwarehouseInfo() {
      comHttp.getStorageName().then((res) => {
        console.log("仓库名称列表", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            depotId: res.result[i].pkStordoc,
          };
          this.storageList.push(data);
        }
      });
    },

    // 处理产成品仓库函数
    setFinishProduct(value, option) {
      let array = value.split("|");
      this.Form.finishedProductDepot = array[1];
      this.Form.finishedProductDepotId = option.key;
      console.log("产成品仓库Id::::", this.Form.finishedProductDepotId);
    },

    // 获取收发类别列表
    getSendReceiveList() {
      // console.log("State:::::",  this.$store.state);

      this.SendReceiveList = [];
      comHttp.getReceiveSendTypeListAll("").then((res) => {
        console.log("收发类别列表:::::", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            value: res.result[i].id,
            title: res.result[i].name,
          };
          this.SendReceiveList.push(data);
        }
      });
    },

    // 获取收发类别Id
    getSendReceiveTypeId(value, options) {
      this.Form.sendReceiveTypeId = options.key;
      console.log("收发类别:::", this.Form.sendReceiveTypeId);
    },

    // 仓库名称选择函数,后同时修改下方表格中的仓库名称和仓库编码
    changeStorageInfo(value, option) {
      let array = value.split("|");
      this.Form.storageNo = array[0];
      this.Form.storage = array[1];
      this.Form.storageId = option.key;
      console.log(" this.Form.storageId", this.Form.storageId);
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].warehouseNumber = array[0];
        this.DataSource[i].warehouse = array[1];
      }
    },

    // 获取物品信息,后期可能会修改为根据仓库id获取物品信息，因为物品信息是根据仓库id来的！！！！！
    // getGoodSInfo(id) {
    //   let goodsList = [];
    //   comHttp.getInventoryInformationByStorageId("?id=" + id).then((res) => {
    //     // console.log("获取存货信息:::::", res);
    //     for (let i = 0; i < res.result.length; i++) {
    //       let data = {
    //         inventoryId: res.result[i].id, // 存货 id
    //         inventoryName: res.result[i].inventoryName,
    //         inventoryNo: res.result[i].inventoryNo,
    //         standardModel: res.result[i].specificationsModel,
    //         unit: res.result[i].unit,
    //       };
    //       goodsList.push(data);
    //     }
    //     console.log(goodsList);
    //   });
    //   return goodsList;
    // },

    //存货编码处理函数
    changeHandleInventory(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      console.log(target);
      // 分割字符串,取出来存货编码
      let array = target.inventory_no.split("|");
      // console.log("存货编码为:::", array[0]);
      target.inventory_no = array[0]; // 赋值给存货编码
      target.inventory_name = array[1]; // 赋值给存货名称
      target.standard_model = array[2]; // 赋值给规格型号
      target.unit = array[3]; // 赋值给单位

      // 根据存货编码获取存货信息::::
    },

    // 获取全部的仓位信息
    getPositionInformationList() {
      comHttp.getPositionInformationList().then((res) => {
        console.log("仓位信息:::::", res);
      });
    },

    // 获取产成品分类
    getFinishGoodsType() {
      comHttp.GetSaveCargoClassification().then((res) => {
        console.log("产成品分类列表", res);

        this.finishGoodsTypeList = res.result;
      });
    },

    // 格式化出库日期
    formatDeliveryDate(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      target.deliveryDate = moment(target.deliveryDate).format("YYYY-MM-DD");
      console.log("修改好的时间为::::", target.deliveryDate);
    },

    // 获取存货信息
    async getInventoryInfo(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      console.log("target===============>", target);
      // 分割字符串,取出来存货编码
      let array = target.inventoryName.split("|");
      target.inventoryNo = array[0]; // 赋值给存货编码
      target.inventoryName = array[1]; // 赋值给存货名称
      // target.standardModel = array[2]; // 赋值给存货名称
      // target.unit = array[3]; // 赋值给存货名称
      // console.log("目标物品信息:::::",target.goodsList)

      // 递归查询出来物品信息
      let goodsInfomation = [];
      for (let i = 0; i < this.goodsList.length; i++) {
        if (this.goodsList[i].inventoryNo == array[0]) {
          goodsInfomation = this.goodsList[i];
        }
      }
      console.log("goodsInfomation===>", goodsInfomation);
      target.standardModel = goodsInfomation.standardModel;
      target.unit = goodsInfomation.unit;

      target.inventoryId = goodsInfomation.inventoryId;
      console.log("存货编码::::", target.inventoryId);

      // if (target.position == "null" || target.position == undefined) {
      //   target.position == "";
      // } else if (
      //   target.sourceNumber == "null" ||
      //   target.sourceNumber == undefined
      // ) {
      //   target.sourceNumber == "";
      // } else if (
      //   target.batchNumber == "null" ||
      //   target.batchNumber == undefined
      // ) {
      //   target.batchNumber == "";
      // } else {
      //   let tempData = {
      //     batchNumber: target.batchNumber,
      //     depotId: parseInt(target.depotId), //仓库Id
      //     inventoryId: parseInt(target.inventoryId), //存货名称
      //     position: parseInt(target.position), //仓位
      //     sourceNumber: target.sourceNumber,
      //   };
      // }
    },
    // 批次号处理列表
    getBatchNumberInfo(key) {
      console.log("111111111111111");
      let tempData = {};
      let target = this.DataSource.filter((item) => item.key === key)[0];
      console.log("target", target);
      if (target.position == "null" || target.position == undefined) {
        target.position == "";
      } else if (
        target.sourceNumber == "null" ||
        target.sourceNumber == undefined
      ) {
        target.sourceNumber == "";
      } else if (
        target.batchNumber == "null" ||
        target.batchNumber == undefined
      ) {
        target.batchNumber == "";
      } else {
        tempData = {
          batchNumber: target.batchNumber,
          depotId: parseInt(target.depotId), //仓库Id
          inventoryId: parseInt(target.inventoryId), //存货名称
          position: parseInt(target.position), //仓位
          sourceNumber: target.sourceNumber,
        };
      }
      comHttp.getExistingQuantity(tempData).then((res) => {
        target.existingQuantity = res.result.balance;
      });
      console.log("this.getExistingQuantity", target.existingQuantity);
    },
    // !获取现存数量
    getExistingQuantity(data) {
      let temp = "";
      // return new Promise((resolve) => {
      comHttp.getExistingQuantity(data).then((res) => {
        temp = res.result.balance;
        console.log("temp", temp);
        console.log("res=================>", res);
        return temp;
        // resolve(temp);
        // });
      });
    },
    // 申请日期
    onChange(date, dateString) {
      console.log(date, dateString);
    },

    // 表格添加新的一条记录
    newMember() {
      this.DataSource.push({
        key: this.DataSource.length + 1,
        isNew: true,

        depotId: "", // 仓库Id
        depotNo: "", // 仓库编码
        depotName: "", // 仓库名称
        depotLocation: "", // 库位
        position: "", // 仓位

        inventoryId: "", // 存货Id
        inventoryNo: "", // 存货编码
        inventoryName: "", //  存货名称
        standardModel: "", // , 规格型号
        unit: "", // 单位

        quantity: "", // 	数量
        unitPrice: "", // 单价
        money: "", // 金额

        batchNumber: "", // 批次号
        finishedProductType: "", //产成品分类
        finishedProductTypeId: "", // 产成品分类Id

        sourceNumber: "", // 源单单号（外键）
        deliveryDate: "", // 出库日期
        remark: "", // 备注

        goodsList: [], // 物品信息列
        BatchList: [], // 批次列表
        positionList: [], // 仓位列表
      });
    },

    // 表格取消一行
    cancle(key) {
      // console.log(key);
      if (this.DataSource.length > 1) {
        this.DataSource.splice(key - 1, 1);
        // 对序号进行重新赋值
        for (let i = key - 1; i < this.DataSource.length; i++) {
          this.DataSource[i].key = i + 1;
        }

        this.$message.success("取消成功");
      } else {
        this.$message.error("至少保留一行");
      }
    },

    // 表格选择事件,
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },

    // 更新表单和物品数据
    updateOrderAndGoodsData() {
      console.log(this.Form);
      // let newData = this.DataSource.filter((item) => item.inventoryNo != "");
      let newData = this.dataSource;
      let updateArray = [];
      console.log("数据：：：：：", newData);
      // 物品
      for (let i = 0; i < newData.length; i++) {
        if (newData[i].isNew == false) {
          let data = {
            id: newData[i].id, // 表二Id
            storageUnit: newData[i].storageUnitId, // 所属仓库
            depotId: newData[i].depotId, // 仓库编码
            depotLocation: newData[i].depotLocation, // 库位
            position: newData[i].position, // 仓位
            inventoryId: newData[i].inventoryId, // 存货编码
            quantity: newData[i].quantity, // 数量
            // 单价
            // 金额
            sourceNumber: newData[i].sourceNumber, // 源单单号
            batchNumber: newData[i].batchNumber, // 批次号
            // finishedProductType: newData[i].finishedProductTypeId, // 产成品分类
            deliveryDate: newData[i].deliveryDate, // 出库日期
            remark: newData[i].remark, // 备注
            amountOfFruitPicking: newData[i].amountOfFruitPicking, // 出菇领料金额
          };
          updateArray.push(data);
        }
      }
      // 单据
      let data = {
        id: this.Form.id,
        document: this.Form.document, // 单据号
        documentDate: moment(this.Form.document_date).format("YYYY-MM-DD"), // 单据日期
        supplier: this.Form.supplierId, // 供应商
        finishedProductDepot: this.Form.finishedProductDepotId, // 产成品仓库
        sendReceiveType: this.Form.sendReceiveTypeId, // 收发类型Id

        responsiblePerson: this.Form.responsiblePersonId, // 负责人Id
        inspector: this.Form.inspectorId, // 审核人(传userid)

        pkCorp: this.Form.pk_corpId, //公司Id
        cwhsmanagerid: this.Form.cwhsmanagerid, //库管员
        pkCalbody: this.Form.pk_calbodyId, //库存组织
        famer: this.Form.farmerId, //农户
        ownedBranch: this.Form.ownedBranchId, //所属分厂
        picker: this.Form.pickerId, //所属分厂
        finishedProductType: this.Form.finishGoodsType, //产成品分类
        // 物品信息
        warehouseReturnRequestFormEntityList: updateArray,
      };

      console.log("要更新的数据::::::", data);
      comHttp.warehousereturnrequest(data).then((res) => {
        if (res.code == 200) {
          this.$message.success("修改成功");
          // this.Reset();
        } else {
          this.$message.error("修改失败");
        }
      });
    },

    // 新增物品数据
    addGoodsData() {
      let newData = this.DataSource.filter((item) => item.inventoryNo != "");
      let addArray = [];
      for (let i = 0; i < newData.length; i++) {
        if (newData[i].isNew == true) {
          let data = {
            otherId: this.otherId, // 表一Id
            storageUnit: newData[i].storageUnitId, // 所属仓库
            depotId: newData[i].depotId, // 仓库编码
            depotLocation: newData[i].depotLocation, // 库位
            position: newData[i].position, // 仓位
            inventoryId: newData[i].inventoryId, // 存货编码
            quantity: newData[i].quantity, // 数量
            // 单价
            // 金额
            sourceNumber: newData[i].sourceNumber, // 源单单号
            batchNumber: newData[i].batchNumber, // 批次号
            finishedProductType: newData[i].finishedProductTypeId, // 产成品分类
            deliveryDate: newData[i].deliveryDate, // 出库日期
            remark: newData[i].remark, // 备注
            amountOfFruitPicking: newData[i].amountOfFruitPicking, // 出菇领料金额
          };
          addArray.push(data);
        }
      }
      // 新增接口
      comHttp.addInOrOutStorageGoods(addArray).then((res) => {
        console.log(res);
      });
    },

    // 获取负责人列表
    getResponsiblePersonList() {
      const roleName = "仓库负责人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.responsiblePersonList.push(data);
        }
      });
    },
    // 设置负责人id
    setResponsible_person(value, options) {
      let array = value.split("|");
      this.Form.responsiblePerson = array[1];
      this.Form.responsiblePersonId = options.key;
    },
    // 获取审核人
    getInspectorList() {
      const roleName = "仓库审核人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.inspectorList.push(data);
          this.inspectorIdList.push(res.result[i].userId);
        }
        if (this.inspectorIdList.indexOf(this.$store.state.user.info.id) > -1) {
          // 按钮状态改变:::::
          console.log(this.ExamineDisplay);
          this.ExamineDisplay = false;
        } else {
          this.ExamineDisplay = true;
        }
      });
    },
    // 设置审核人id
    setInspector(value, options) {
      let array = value.split("|");
      this.Form.inspector = array[1];
      this.Form.inspectorId = options.key;
    },

    // 重置
    Reset() {
      // 重置表单
      this.Form = {
        document: "", // 申请单号
        document_date: moment().format("YYYY-MM-DD"), // 单据日期 // 日期, // 单据日期
        sendReceiveType: "", // 收发类别名称
        sendReceiveTypeId: "", // 收发类别Id
        finishedProductDepot: "", //产成品仓库
        finishProductInventoryNo: "", //产成品仓库编码
        finishedProductDepotId: "", //产成品仓库ID
        supplier: "", //供应商
        supplierId: "", //供应商Id

        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        balance: moment().format("YYYY-MM-DD"), // 审核日期
        singleProducer: this.$store.state.user.info.username, // 制单人名称
        singleProducerId: this.$store.state.user.info.id, // 制单人Id
      };
      // 重置表格
      this.dataSource = [];
      // 重新加载单据号
      this.getApplyOrder();
      // 重新设置表格列
      this.setColumns();
    },

    // --------------------

    // 保存
    Save() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.$refs.ruleForm2.validate((valid2) => {
            if (valid2) {
              // 通过更新标志来控制，是否是路由跳转过来的，还是新打开的页面
              // 如果是路由跳转过来的，那就是在原有的基础上进行修改，走修改接口和新增接口，修改物品和新增订单物品
              // 如果不是路由跳转过来的，走新增两个接口，新增订单和新增订单物品
              if (this.updateTag) {
                // 新增数据,新增表单数据和物品数据
                this.addOrderDataAndGoodsData();
              } else {
                this.updateOrderAndGoodsData(); // 更新表单和物品数据
                this.addGoodsData(); // 新增物品数据
              }
            }
          });
        }
      });
    },

    // 新增数据,新增表单数据和物品数据
    addOrderDataAndGoodsData() {
      // 过滤物品编码
      // let newData = this.DataSource.filter((item) => item.inventoryNo != "");
      let newData = this.dataSource;
      console.log("newData=====>", newData);
      let array = [];

      for (let i = 0; i < newData.length; i++) {
        // if (
        //   newData[i].storageUnitId == "undefined" ||
        //   newData[i].storageUnitId == "null" ||
        //   newData[i].storageUnitId == ""
        // ) {
        //   this.$message.error("请选择所属仓库！");
        // } else
        if (
          newData[i].depotId == "undefined" ||
          newData[i].depotId == "null" ||
          newData[i].depotId == ""
        ) {
          this.$message.error("请选择仓库单位！");
        } else if (
          newData[i].inventoryId == "undefined" ||
          newData[i].inventoryId == "null" ||
          newData[i].inventoryId == ""
        ) {
          this.$message.error("请选择存货编码 ！");
        } else if (
          newData[i].quantity == "undefined" ||
          newData[i].quantity == "null" ||
          newData[i].quantity == ""
        ) {
          this.$message.error("请填写存货数量 ！");
        } else if (
          newData[i].batchNumber == "undefined" ||
          newData[i].batchNumber == "null"
        ) {
          this.$message.error("请选择批次号 ！");
        } else if (
          newData[i].deliveryDate == "undefined" ||
          newData[i].deliveryDate == "null" ||
          newData[i].deliveryDate == ""
        ) {
          this.$message.error("请填写出库日期 ！");
        } else {
          let data = {
            objectInformationId: newData[i].objectInformationId, //据源单生成的物品列表接口中

            storageUnit: newData[i].storageUnitId, // 所属仓库
            depotId: newData[i].depotId, // 仓库ID
            depotLocation: newData[i].depotLocation, // 库位
            position: newData[i].position, // 仓位
            inventoryId: newData[i].inventoryId, // 存货Id
            quantity: newData[i].quantity, // 数量
            // 单价
            // 金额
            sourceNumber: newData[i].sourceNumber, // 源单单号
            batchNumber: newData[i].batchNumber, // 批次号
            finishedProductType: newData[i].finishedProductType, // 产成品分类
            deliveryDate: newData[i].deliveryDate, // 出库日期
            remark: newData[i].remark, // 备注
            amountOfFruitPicking: newData[i].amountOfFruitPicking, // 出菇领料金额
            // pickingContentId:this.Form.pickingContentId, //生产领料表单物品ID

            pickingContentId: newData[i].pickingContentId, //生产领料表单物品ID
          };
          array.push(data);
        }
      }
      let AllData = {
        balance: moment(this.Form.document_date).format("YYYY-MM-DD"),
        auditMark: 2, // 审核标志, 1 已审核,2 未审核
        bookkeepingMark: 2, // 记账标志 , 1 已记账 , 2 未记账
        inOutCategoryIdentification: 9, // 入库、出库类别标识, 1-6 采购入库、产成品入库、销售出库、生产材料出库、基建出库、其他出库
        inOutIdentification: 3, // 入库、出库标识，1 入库，2 出库

        document: this.Form.document, // 单据号
        documentDate: moment(this.Form.document_date).format("YYYY-MM-DD"), // 单据日期
        supplier: this.Form.supplierId, // 供应商
        finishedProductDepot: this.Form.finishedProductDepotId, // 产成品仓库
        sendReceiveType: this.Form.sendReceiveTypeId, // 收发类型Id

        responsiblePerson: this.Form.responsiblePersonId, // 负责人Id
        inspector: this.Form.inspectorId, // 审核人(传userid)
        singleProducer: this.Form.singleProducerId, // 制单人(传userid)

        pkCorp: this.Form.pk_corpId, //公司Id
        cwhsmanagerid: this.Form.cwhsmanagerid, //库管员
        pkCalbody: this.Form.pk_calbodyId, //库存组织
        famer: this.Form.farmerId, //农户
        ownedBranch: this.Form.ownedBranchId, //所属分厂
        picker: this.Form.pickerId, //领料员
        finishedProductType: this.Form.finishGoodsType, //产成品分类
        // 物品信息
        warehouseReturnRequestFormEntityList: array,
      };

      console.log("全部的数据", AllData);
      comHttp.saveStockReturnInfo(AllData).then((res) => {
        if (res.code == 200) {
          this.$message.success("提交成功");
          this.Reset();
        } else {
          this.$message.error("提交失败");
        }
      });
    },

    // ---------  写好的 --------------
    // 获取单号
    getApplyOrder() {
      let queryPath = "?string=SCCKTS-";
      comHttp.getOrder(queryPath).then((res) => {
        this.Form.document = res.message;
      });
    },

    // 设置所属仓库, 上面表单触发事件
    setdataSourcestorageUnit(value, option) {
      let array = value.split("|");
      this.Form.storageUnit = array[1];
      // console.log(array[0]);
      let key = option.key;
      console.log(key);
      // option.key
      // 根据仓库查询物品信息,并存储到相应的物品信息表中
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].storageUnitNo = array[0];
        this.DataSource[i].storageUnit = array[1];
        this.DataSource[i].storageUnitId = option.key;
      }
      console.log("赋值好的表格内容:::::", this.DataSource);
    },
    // 表单仓库点击按钮 -------- 上方选择仓库后，下方物品都填入该仓库
    setdataSourceDepartment(value, option) {
      let array = value.split("|");
      console.log(array[0]);
      this.Form.depotNo = array[0];
      this.Form.depotName = array[1];
      let key = option.key;
      // 获取物品信息列表,根据仓库编码
      // let goodsList = this.getGoodSInfo(key);

      // option.key
      // 根据仓库查询物品信息,并存储到相应的物品信息表中
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].depotNo = array[0];
        this.DataSource[i].depotName = array[1];
        this.DataSource[i].depotId = key;

        this.DataSource[i].goodsList = this.goodsList;
      }
      console.log("赋值好的表格内容:::::", this.DataSource);
    },
    // 获取供应商列表
    getSupplierInfo() {
      comHttp.getSupplierInfo().then((res) => {
        console.log("供应商列表-》》》", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            supplierId: res.result[i].id,
            suppilerCode: res.result[i].suppilerCode,
            suppilerName: res.result[i].suppilerName,
          };
          this.supplierList.push(data);
        }
      });
    },
    // 获取供应商信息
    getSupplierId(value, option) {
      let array = value.split("|");
      this.Form.supplier = array[1]; //供应商名称
      this.Form.supplierCode = array[0]; //供应商编码
      this.Form.supplierId = option.key;
      console.log("供应商Id:", this.Form.supplierId);
    },

    // 设置存货列表
    async setGoodsList(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      let array = target.depotNo.split("|");
      target.depotNo = array[0]; // 仓库编码
      target.depotName = array[1]; // 仓库名称

      let SotrageInfo = this.storageList.filter(
        (item) => item.depotNo === array[0]
      )[0];
      target.depotId = SotrageInfo.depotId;

      // 仓库Id
      console.log("仓库Id:::", target.depotId);
      // 设置好存货
      // let goodsList = this.getGoodSInfo(target.depotId);
      target.goodsList = this.goodsList;
      console.log("存货列表:::", target.goodsList);
      // 设置好仓位
      let positionList = await this.getPositionList(target.depotId);
      console.log("positionListpositionList===>", positionList);
      let TempList = await this.disableParent(positionList);
      target.positionList = TempList;
      console.log("仓位列表:::", target.positionList);
    },

    // 获取产成品分类Id
    getFinishGoodsTypeId(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      console.log("item.dataType--------->", target);
      // let array = [];
      // array = target.finishedProductType.split("|");
      // target.finishedProductTypeId = parseInt(array[0]);
      // target.finishedProductType = array[1];
      // console.log("产成品分类ID", target.finishedProductTypeId);
    },
    // 删除
    Delete(id) {
      comHttp.deleteInOrOutStorageGoods("?id=" + id).then((res) => {
        if (res && res.code === 200) {
          this.$message.success("删除成功");
          this.setInitInfo(this.$route.query.Id);
        } else {
          this.$message.error("删除失败");
        }
      });
    },

    // 禁用父节点
    disableParent(Tree) {
      return new Promise((resolve) => {
        Tree.forEach((item) => {
          console.log(item);
          if (item.children.length != 0) {
            item[`disabled`] = true;
          } else {
            this.disableParent(item.children);
          }
        });
        resolve(Tree);
      });
    },

    // 获取仓位列表
    getPositionList(id) {
      console.log(id);
      let positionList = [];
      return new Promise((resolve) => {
        comHttp.getPositionInformationListByDepotId("?id=" + id).then((res) => {
          console.log("res", res);
          if (res.result.length != 0) {
            positionList = res.result[0].children;
            resolve(positionList);
          } else {
            let falseTag = 1;
            resolve(falseTag);
          }
        });
      });
    },

    // 获取源单数据
    async getOriginData(data) {
      // let newData = this.DataSource.filter((item) => item.depotNo != "");
      this.DataSource = [];

      // this.DataSource = newData;
      console.log("this.DataSource", this.DataSource);
      console.log("data", data);
      console.log("data.length", data.length);
      let tempArr = [];
      tempArr = data;
      for (let i = 0; i < data.length; i++) {
        // if(this.DataSource[i].)
        tempArr[i].key = i + 1;
        tempArr[i].storageUnitId = data[i].affiliationId;
        tempArr[i].storageUnit = data[i].affiliation;
        tempArr[i].depotId = data[i].depotId;
        tempArr[i].depotNo = data[i].depotNo;
        tempArr[i].depotName = data[i].warehouse;
        tempArr[i].depotLocation = data[i].depotLocation;
        tempArr[i].position = data[i].position;
        tempArr[i].inventoryId = data[i].inventoryId;
        tempArr[i].inventoryNo = data[i].Number;
        // tempArr[i].Number = data[i].Number;
        tempArr[i].inventoryName = data[i].goodName;
        tempArr[i].standard = data[i].standard;
        tempArr[i].unit = data[i].unit;
        tempArr[i].quantity = data[i].number2;
        tempArr[i].price = data[i].price;
        tempArr[i].money = data[i].price;
        tempArr[i].finishedProductType = data[i].finishGoodsType;
        tempArr[i].remark = data[i].remark;
        console.log("tempArr", tempArr);
        // this.DataSource = tempArr;
        // 获取仓位、库位列表
        console.log("data[i].depotId", data[i].depotId);
      }
      // console.log("tempData", tempData);
      this.DataSource = this.DataSource.concat(tempArr);
      console.log("this.DataSource=====!!!!!!!", this.DataSource);
    },
  },
};
</script>

<style></style>
